<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>在线答题</title>
  <link rel="stylesheet" href="/static/web/css/style.css?v=" + Date.now() >
  <script src="/static/component/jquery_3.3.1.js"></script>
  <style type="text/css">
    /* 答题卡右侧布局 */
.layout-flex {
  display: flex;
  gap: 20px;
}

.main-content {
  flex: 1;
}

.card-sidebar {
  width: 180px;
  background: #fff;
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}

/* 答题卡分数区域 */
.score-box {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 10px;
  text-align: center;
}

/* 正确题绿色，错误题红色 */
.card-item.correct {
  background-color: #28a745 !important;
}
.card-item.wrong {
  background-color: #dc3545 !important;
}

/* 已作答题号标蓝色 */
.card-item.answered {
  background-color: #007bff !important;
  color: white;
}

/* 提交结果弹出卡片 */
.result-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.result-card {
  background: white;
  padding: 150px;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  font-size: 18px;
  // 调整卡片尺寸为更协调的比例
  width: 800px;
  height: 200px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.result-card h3 {
  margin-top: 0;
  margin-bottom: 26px;
}

.result-card .user-info {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 10px;
}

.result-card .score {
  font-size: 20px;
  color: #007bff;
  font-weight: bold;
}

/* 按钮样式 */
.nav-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  gap: 10px; /* 添加按钮间距 */
}

.nav-buttons button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.nav-buttons #prev, 
.nav-buttons #next {
  background-color: #007bff; /* 蓝色背景 */
  color: white;
}

.nav-buttons #prev:disabled, 
.nav-buttons #next:disabled {
  background-color: #cccccc; /* 灰色背景 */
  cursor: not-allowed;
}

.nav-buttons #submit {
  background-color: #28a745; /* 绿色背景 */
  color: white;
  margin-left: auto; /* 将按钮推向右侧 */
}

  </style>
</head>
<body class="container">
  <h2>📝 在线答题</h2>
  <div id="user-info">姓名：<span id="user-name">张三</span>  | 证件号码：<span id="user-idcard">123456789</span> ｜ 剩余时间：<span id="timer" style="color: red">00:00</span></div>

<div class="layout-flex">
  <div class="main-content">
    <div id="question-box" class="question"></div>
    <div class="nav-buttons">
      <button id="prev">上一题</button>
      <button id="next">下一题</button>
      <button id="submit" onclick="submit()">提交试卷</button>
    </div>
  </div>

  <div class="card-sidebar">
    <div class="score-box" id="score"></div>
    <h3>答题卡</h3>
    <div id="card" class="answer-card"></div>
  </div>
</div>

<script src="/static/web/js/layout.js?v=" + Date.now() ></script>

  <script>
    let current = 0, answers = {}, questions = [];
    // 将 paperId 声明为全局变量
    let paperId = 0, examId = 0, totalScore = 0, duration = 0;

    let userInfo = [];
    // 修改为异步获取用户信息
    $.ajax({
      url: '/web.profile/info',
      method: 'GET',
      dataType: 'json'
    }).then(function(result) {
      userInfo = result.data;
      // 动态设置用户姓名
      $('#user-name').text(userInfo.name);
      $('#user-idcard').text(userInfo.id_card);

    }).catch(function(error) {
      console.error("获取用户信息失败：", error);
    });

 function loadQuestion(index) {
  const q = questions[index];
  let html = `<h4>第${index + 1}题（${q.type}）：${q.title}</h4>`;
  
  if (q.type === "简答题" || q.type === "填空题") {
    // 修改为基于试题ID获取答案
    const ans = answers[q.id]?.[0] || "";
    html += `<textarea name="opt" rows="5" style="width:100%">${ans}</textarea>`;
  } else {
    q.options.forEach((opt, i) => {
      // 修改为基于试题ID检查答案
      const checked = answers[q.id]?.includes(i) ? "checked" : "";
      const type = q.type === "多选题" ? "checkbox" : "radio";
      html += `<label><input type="${type}" name="opt" value="${i}" ${checked}> ${opt}</label><br>`;
    });
  }

  $("#question-box").html(html);
  
  // 更新按钮状态
  updateButtonStatus();
}

// 新增函数：更新按钮状态
function updateButtonStatus() {
  // 上一题按钮状态
  if (current === 0) {
    $("#prev").prop("disabled", true);
  } else {
    $("#prev").prop("disabled", false);
  }
  
  // 下一题按钮状态
  if (current === questions.length - 1) {
    $("#next").prop("disabled", true);
  } else {
    $("#next").prop("disabled", false);
  }
}

function updateAnswer() {
  if ($("input[name='opt']").first().attr("type") === "checkbox" || $("input[name='opt']").first().attr("type") === "radio") {
    const checked = $("input[name='opt']:checked").map((_, el) => parseInt($(el).val())).get();

    if (checked.length > 0) {
      // 修改为保存试题ID和用户答案
      answers[questions[current].id] = checked;
    } else {
      delete answers[questions[current].id];
    }
  }

  // 添加对textarea元素的直接检测，确保填空题和简答题的答案被正确收集
  if ($("textarea[name='opt']").length > 0) {
    const textValue = $("textarea[name='opt']").val();
    if (textValue && textValue.trim() !== "") {
      answers[questions[current].id] = [textValue];
    } else {
      delete answers[questions[current].id];
    }
  }


  // 更新答题卡状态
  renderCard();
}

    function renderCard(result = null) {
      $("#card").html("");
      questions.forEach((q, i) => {
    let colorClass = "";
    if (result) {
      colorClass = result[q.id] ? "correct" : "wrong";
    } else {
      // 修改为基于试题ID检查是否有答案
      const hasAnswer = answers[q.id] && answers[q.id].length > 0 && 
                        (q.type !== "简答题" || (q.type === "简答题" && answers[q.id][0].trim() !== ""));
      colorClass = hasAnswer ? "answered" : "";
    }
    $("#card").append(`<span class="card-item ${colorClass}" onclick="jump(${i})">${i + 1}</span>`);
  });
}


function submit() {
  updateAnswer();

  // 构建提交数据
  const submitData = {
    examId: examId,
    paperId: paperId,
    answers: answers
  };
  // 提交到web.Exam/yuePaper接口

  console.log(submitData);
  $.ajax({
    url: '/web.Exam/yuePaper',
    method: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(submitData),
    success: function(response) {
      if (response.code === 0) {
        const score = response.data.score;
        const result = response.data.result;
        
        renderCard(result);
        
        const resultModal = `
          <div class="result-modal" id="resultModal">
            <div class="result-card">
              <h2>考试得分情况</h2>
              <div class="user-info">姓名：<span id="user-name">${userInfo.name}</span> </div>
              <div class="user-info">证件号码：<span id="user-idcard">${userInfo.id_card}</span> </div>
              <div class="score">得分：${score} / ${totalScore}</div>
            </div>
          </div>
        `;
        $("body").append(resultModal);
        
        // 点击弹出卡片外部关闭
        $("#resultModal").click(function(e) {
          if (e.target === this) {
            $(this).remove();
          }
        });
      } else {
        alert("提交失败: " + response.msg);
      }
    },
    error: function() {
      alert("提交试卷失败，请检查网络连接或联系管理员");
    }
  });
}

    function jump(i) {
      updateAnswer(); current = i;
      loadQuestion(current); renderCard();
    }


    function startTimer(duration) {
      let timer = duration, minutes, seconds;
      const interval = setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);
        $('#timer').text(`${minutes}:${seconds < 10 ? "0" + seconds : seconds}`);
        if (--timer < 0) {
          clearInterval(interval);
          submit();
        }
      }, 1000);
    }

    $(function () {
      const urlParams = new URLSearchParams(window.location.search);

      examId = urlParams.get('examId');
      paperId = urlParams.get('paperId');
      // 添加成功和失败处理
      $.getJSON("/web.Exam/paperInfo?paperId=" + paperId + "&examId=" + examId)
        .done(function (result) {
          // 请求成功处理
          if (result.code === 0) {
            questions = result.data.questions;
            totalScore = result.data.paperInfo.total_score;
            duration = result.data.examInfo.duration;
            loadQuestion(0);
            renderCard();
            startTimer(duration * 60);
          } else {
            // 服务器返回错误信息处理
            alert("获取试卷信息失败: " + result.msg);
            window.location.href = "/web/examList.html";

          }
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
          // 请求失败处理
          alert("获取试卷信息失败，请检查网络连接或联系管理员");
         window.location.href = "/web/examList.html";
        });
    });

    $("#prev").click(() => {
      updateAnswer(); if (current > 0) current--;
      loadQuestion(current); renderCard();
    });

    $("#next").click(() => {
      updateAnswer(); if (current < questions.length - 1) current++;
      loadQuestion(current); renderCard();
    });
  </script>
</body>
</html>